var EditCanvas = new function(){

	var MAX_WIDTH = 1600;
	var MAX_HEIGHT = 1600;

	var width;
	var height;
	
	var director;
	var scene;
	var foregroundLayer;
	var centerLayer;
	var entityLayer;
	var backgroundLayer;
	var gridLayer;
	
	var hScrollByPx = true;
	var vScrollByPx = true;
	
	var offsetX;
	var offsetY;
	
	var hScrollPx;
	var vScrollPx;
	
	var loadedSprites = {};
	
	var lX = -1;
	var lY = -1;
	var lPosX = -1;
	var lPosY = -1;
	
	var sNrX = -1;
	var sNrY = -1;
	
	var cvsClick = false;
	
	var drawhint;
	
	this.init = function(){
	
		Tools.selectedTool = 2;
	
		cvsClick = false;
	
		offsetX = 0;
		offsetY = 0;
		
		hScrollPx = 0;
		vScrollPx = 0;
		
		selectedBox = -1;
	
		width = $("#Creator_canvas").innerWidth();
		height = $("#Creator_canvas").innerHeight();
		
		director = new CAAT.Director().initialize(
			width,
			height,
			document.getElementById("Creator_canvas")
		);
		
		scene = director.createScene();
		
		bgImageLayer = new CAAT.ActorContainer().
				setBounds(0,0,MAX_WIDTH,MAX_HEIGHT);
		
		backgroundLayer = new CAAT.ActorContainer().
				setBounds(0,0,MAX_WIDTH,MAX_HEIGHT);
		centerLayer = new CAAT.ActorContainer().
				setBounds(0,0,MAX_WIDTH,MAX_HEIGHT);
		entityLayer = new CAAT.ActorContainer().
				setBounds(0,0,MAX_WIDTH,MAX_HEIGHT);
		foregroundLayer = new CAAT.ActorContainer().
				setBounds(0,0,MAX_WIDTH,MAX_HEIGHT);
				
		scene.addChild(bgImageLayer);
		scene.addChild(backgroundLayer);
		scene.addChild(centerLayer);
		scene.addChild(entityLayer);
		scene.addChild(foregroundLayer);
		
		drawhint = new CAAT.ShapeActor().
				setLocation(0,0).
				setSize(16,16).
				setFillStyle('rgba(7,138,162,0.25)').
				setShape(CAAT.ShapeActor.prototype.SHAPE_RECTANGLE).
				setStrokeStyle('rgba(7,138,162,0.75)').
				setVisible(false);
		
		scene.addChild(drawhint);
		
		gridLayer = getGrid();
		
		bgImageLayer.setGlobalAlpha(true);
		backgroundLayer.setGlobalAlpha(true);
		centerLayer.setGlobalAlpha(true);
		entityLayer.setGlobalAlpha(true);
		foregroundLayer.setGlobalAlpha(true);
		gridLayer.setGlobalAlpha(true);
		
		scene.addChild(gridLayer);
 
		director.loop(1);
		director.endLoop();
		
		if(MAX_WIDTH <= $("#Creator_canvas").innerWidth()){
			hideHScroller();
		} else {
			showHScroller();
		}
		if(MAX_HEIGHT <= $("#Creator_canvas").innerHeight()){
			hideVScroller();
		} else {
			showVScroller();
		}
		
		
		
		var scrollerHMoving = false;
		var scrollerVMoving = false;
		var scrollerHMover;
		var scrollerVMover;
		var scrollerStartX = 0;
		var scrollerStartY = 0;
		var scrollerStartLeft = 0;
		var scrollerStartTop = 0;
		
		
		$("#Creator_hScrollbar .scroller").on("mousedown",function(e){
			scrollerHMover = $(this);
			scrollerHMoving = true;
			scrollerStartX = e.pageX;
			scrollerStartLeft = scrollerHMover.position().left;
			
			$("body").css("cursor","pointer");
		});
		
		$("#Creator_vScrollbar .scroller").on("mousedown",function(e){
			scrollerVMover = $(this);
			scrollerVMoving = true;
			scrollerStartY = e.pageY;
			scrollerStartTop = scrollerVMover.position().top;
			
			$("body").css("cursor","pointer");
		});
		
		$("#Creator_toolbar_tools i").not(".disabled").on("click", function(){
			$("#Creator_toolbar_tools i").removeClass("active");
			$(this).addClass("active");
			Tools.selectedTool = parseInt($(this).attr("toolId"));
		});
				
		$("#Creator_canvas").on("mousedown", function(e){
			cvsClick = true;
			
			var totX = e.offsetX + offsetX;
			sNrX = Math.floor(totX/16);
			var totY = e.offsetY + offsetY;
			sNrY = Math.floor(totY/16);
		});
		
		$("#Creator_canvas").on("click", function(e){
			switch(Tools.selectedTool){
				case 1:
					//TODO: select
					break;
				case 2:
				case 3:
					if(Tools.selectedBox >= 0){
						draw(e.offsetX, e.offsetY);
					} else if(Tools.selectedEntity >= 0){
						setEntity(e.offsetX, e.offsetY);
					}
					break;
				case 4:
				case 5:
					if(Tools.selectedBox >= 0){
						erase(e.offsetX, e.offsetY);
					} else if(Tools.selectedEntity >= 0){
						removeEntity(e.offsetX, e.offsetY);
					}
					break;
				default:
					break;
			}
		});
		
		$("*").on("mousemove",function(e){
		
			if(e.target.id == "Creator_canvas" && Tools.selectedBox >= 0){
				
			
				if((Tools.selectedTool == 3 || Tools.selectedTool == 5) && cvsClick){
					
					var totX = e.offsetX + offsetX;
					var nrX = Math.floor(totX/16);
					var totY = e.offsetY + offsetY;
					var nrY = Math.floor(totY/16);
					var nrXs;
					var nrYs;
					
					if(nrX < sNrX){
						nrXs = nrX;
						nrX = sNrX;
					} else {
						nrXs = sNrX;
					}
					if(nrY < sNrY){
						nrYs = nrY;
						nrY = sNrY;
					} else {
						nrYs = sNrY;
					}
					
					drawhint.
						setLocation(nrXs*16-offsetX,nrYs*16-offsetY).
						setSize((1+nrX-nrXs) * 16,(1+nrY-nrYs) * 16).
						setVisible(true);
					
				} else {
				
					var nrX = Math.floor(e.offsetX/16);
					var nrY = Math.floor(e.offsetY/16);
			
					drawhint.
						setLocation(nrX*16,nrY*16).
						setSize(16,16).
						setVisible(true);
					
				}
				
			} else {
				drawhint.setVisible(false);
			}
		
			if(scrollerHMoving){
				var dX = e.pageX - scrollerStartX;
				
				var newLeft = scrollerStartLeft + dX;
				
				var maxWidth = $("#Creator_hScrollbar").innerWidth() - scrollerHMover.innerWidth();
				
				if(newLeft > maxWidth) newLeft = maxWidth;
				if(newLeft < 0) newLeft = 0;
				
				scrollerHMover.css("left",newLeft + "px");
				
				if(hScrollByPx){
					offsetX = newLeft;
					EditCanvas.redraw();
				} else {
					var perc = newLeft / maxWidth;
					offsetX = Math.round(hScrollPx * perc);
					offsetX = Math.round(offsetX / 16.)*16;
					EditCanvas.redraw();
				}
				
			}
			
			if(scrollerVMoving){
				var dY = e.pageY - scrollerStartY;
				
				var newTop = scrollerStartTop + dY;
				
				var maxHeight = $("#Creator_vScrollbar").innerHeight() - scrollerVMover.innerHeight();
				
				if(newTop > maxHeight) newTop = maxHeight;
				if(newTop < 0) newTop = 0;
				
				scrollerVMover.css("top",newTop + "px");
				
				if(vScrollByPx){
					offsetY = newTop;
					EditCanvas.redraw();
				} else {
					var perc = newTop / maxHeight;
					offsetY = Math.round(vScrollPx * perc);
					offsetY = Math.round(offsetY / 16.)*16;
					EditCanvas.redraw();
				}
				
			}
			
			if(cvsClick){
				
				switch(Tools.selectedTool){
					case 1:
						break;
					case 2:
						if(e.target.id == "Creator_canvas"){
							if(Tools.selectedBox >= 0){
								draw(e.offsetX, e.offsetY);
							}
						} else {
							lX = -1;
							lY = -1;
						}
						break;
					case 3:
						break;
					case 4:
						if(e.target.id == "Creator_canvas"){
							if(Tools.selectedBox >= 0){
								erase(e.offsetX, e.offsetY);
							}
						} else {
							lX = -1;
							lY = -1;
						}
						break;
					case 5:
						break;
					default:
						break;
				}
			
			
				
			}
			
		});
		
		$("*").on("mouseup",function(e){
		
			if(cvsClick){
			
				var totX = e.offsetX + offsetX;
				var nrX = Math.floor(totX/16);
				var totY = e.offsetY + offsetY;
				var nrY = Math.floor(totY/16);
				
				var temp;
				
				if(sNrX > nrX){
					temp = sNrX;
					sNrX = nrX;
					nrX = temp;
				}
				if(sNrY > nrY){
					temp = sNrY;
					sNrY = nrY;
					nrY = temp;
				}
				
				switch(Tools.selectedTool){
					case 1:
						break;
					case 2:
						break;
					case 3:
						if(e.target.id == "Creator_canvas"){
							for(var i = sNrX; i <= nrX; i++){
								for(var j = sNrY; j <= nrY; j++){
									putBox(i, j);
								}
							}
						}
						refresh();
						break;
					case 4:
						break;
					case 5:
						if(e.target.id == "Creator_canvas"){
							for(var i = sNrX; i <= nrX; i++){
								for(var j = sNrY; j <= nrY; j++){
									eraseBox(i, j);
								}
							}
						}
						refresh();
						break;
					default:
						break;
				}
			
			
				
			}
		
			scrollerHMoving = false;
			scrollerVMoving = false;
			cvsClick = false;
			$("body").css("cursor","auto");
			lX = -1;
			lY = -1;
		});
		
		refresh();
	};
	
	this.stop = function(){
		director.endLoop();
		director.destroy();
	};
	
	var refresh = function(){
	
		backgroundLayer.emptyChildren();
		centerLayer.emptyChildren();
		entityLayer.emptyChildren();
		foregroundLayer.emptyChildren();
		
		var images = {};
	
		for(var i = 0; i < WGC.data.sprite.length; i++){
			var s = WGC.data.sprite[i];
			if(s && !loadedSprites[s.spriteId])
				images[s.spriteId] = s.image;
		}
		
		H5.preloadImages(images, function(imgs){
				
			for(var i in imgs){
				loadedSprites[i] = new CAAT.SpriteImage().
							initialize(imgs[i], 1, WGC.data.sprite[i].frames).
							setChangeFPS(WGC.data.sprite[i].fps);
			}
			for(var i = 0; i < WGC.data.gamebox.length; i++){
		
				var gb = WGC.data.gamebox[i];
				if(gb){
					var gbs = WGC.data.gameboxstate[gb.defaultStateId];
					if(gbs){
						var b = WGC.data.box[gbs.boxId];
						var s = WGC.data.sprite[b.spriteId];
						
						var actor = new CAAT.Actor().
								setBackgroundImage(loadedSprites[s.spriteId].getRef()).
								enableEvents(false).
								setPosition(gb.posX*16, gb.posY*16);
						
						switch(gb.gameBoxLayerId){
							case WGC.data.game.backgroundLayerId:
								backgroundLayer.addChild(actor);
								break;
							case WGC.data.game.centerLayerId:
								centerLayer.addChild(actor);
								break;
							case WGC.data.game.foregroundLayerId:
								foregroundLayer.addChild(actor);
								break;
							default:
								break;
						}
						
					}
				}
			}
			for(var i = 0; i < WGC.data.gameentity.length; i++){
				var ge = WGC.data.gameentity[i];
				if(ge){
					var e = WGC.data.entity[ge.entityId];
					if(e){
						var es = WGC.data.entitystate[e.defaultStateId];
						var s = WGC.data.sprite[es.spriteId];
												
						var actor = new CAAT.Actor().
								setBackgroundImage(loadedSprites[s.spriteId].getRef()).
								enableEvents(false).
								setPosition(ge.posX - s.width/2, ge.posY - s.height/2);
								
						entityLayer.addChild(actor);
					}
				}
			}
			
		}, function(e){
			H5.Log.error(e);
		});
			
		EditCanvas.redraw();
	};
	
	this.redraw = function(){
		switch(Tools.visibility.bgImage){
			case 0:
				bgImageLayer.setVisible(false);
				break;
			case 1:
				bgImageLayer.setVisible(true);
				bgImageLayer.setAlpha(0.5);
				break;
			case 2:
				bgImageLayer.setVisible(true);
				bgImageLayer.setAlpha(1);
				break;
		}
		switch(Tools.visibility.background){
			case 0:
				backgroundLayer.setVisible(false);
				break;
			case 1:
				backgroundLayer.setVisible(true);
				backgroundLayer.setAlpha(0.5);
				break;
			case 2:
				backgroundLayer.setVisible(true);
				backgroundLayer.setAlpha(1);
				break;
		}
		switch(Tools.visibility.center){
			case 0:
				centerLayer.setVisible(false);
				break;
			case 1:
				centerLayer.setVisible(true);
				centerLayer.setAlpha(0.5);
				break;
			case 2:
				centerLayer.setVisible(true);
				centerLayer.setAlpha(1);
				break;
		}
		switch(Tools.visibility.foreground){
			case 0:
				foregroundLayer.setVisible(false);
				break;
			case 1:
				foregroundLayer.setVisible(true);
				foregroundLayer.setAlpha(0.5);
				break;
			case 2:
				foregroundLayer.setVisible(true);
				foregroundLayer.setAlpha(1);
				break;
		}
		switch(Tools.visibility.grid){
			case 0:
				gridLayer.setVisible(false);
				break;
			case 1:
				gridLayer.setVisible(true);
				gridLayer.setAlpha(0.25);
				break;
			case 2:
				gridLayer.setVisible(true);
				gridLayer.setAlpha(1);
				break;
		}
	
		backgroundLayer.setPosition(-offsetX, -offsetY);
		centerLayer.setPosition(-offsetX, -offsetY);
		entityLayer.setPosition(-offsetX, -offsetY);
		foregroundLayer.setPosition(-offsetX, -offsetY);
		
		director.loop(1);
		director.endLoop();
	};
	
	
	var draw = function(posX, posY){
		
		var totX = posX + offsetX;
		var nrX = Math.floor(totX/16);
		var totY = posY + offsetY;
		var nrY = Math.floor(totY/16);
		
		if(lX != nrX || lY != nrY){
		
			//make lines between points, needs too much performance...
			/*if(lX != -1 && lY != -1 && (Math.abs(lX - nrX) > 1 || Math.abs(lY - nrY) > 1)){
				var dX = posX - lPosX;
				var dY = posY - lPosY;
				var steps = Math.round(Math.sqrt(dX*dX + dY*dY)/4);
				for(var i = 0; i < steps && cvsClick; i++){
					var totXb = lPosX + offsetX + (dX/steps)*i;
					var nrXb = Math.floor(totXb/16);
					var totYb = lPosY + offsetY + (dY/steps)*i;
					var nrYb = Math.floor(totYb/16);
					
					putBox(nrXb, nrYb);
					
					lX = nrXb;
					lY = nrYb;
				}
			}*/
		
			putBox(nrX, nrY);
			
			lX = nrX;
			lY = nrY;
			
				
			refresh();
		}
		
		lPosX = posX;
		lPosY = posY;
		
	};
	
	var erase = function(posX, posY){
	
		var totX = posX + offsetX;
		var nrX = Math.floor(totX/16);
		var totY = posY + offsetY;
		var nrY = Math.floor(totY/16);
		
		if(lX != nrX || lY != nrY){
		
			//make lines between points, needs too much performance...
			/*if(lX != -1 && lY != -1 && (Math.abs(lX - nrX) > 1 || Math.abs(lY - nrY) > 1)){
				var dX = posX - lPosX;
				var dY = posY - lPosY;
				var steps = Math.round(Math.sqrt(dX*dX + dY*dY)/4);
				for(var i = 0; i < steps && cvsClick; i++){
					var totXb = lPosX + offsetX + (dX/steps)*i;
					var nrXb = Math.floor(totXb/16);
					var totYb = lPosY + offsetY + (dY/steps)*i;
					var nrYb = Math.floor(totYb/16);
					
					eraseBox(nrXb, nrYb);
					
					lX = nrXb;
					lY = nrYb;
				}
			}*/
		
			eraseBox(nrX, nrY);
			
			lX = nrX;
			lY = nrY;
			
				
			refresh();
		}
		
		lPosX = posX;
		lPosY = posY;
	
	};
	
	var putBox = function(nrX, nrY){
	
		if(lX != nrX || lY != nrY){
	
			if(WGC.data.box[Tools.selectedBox]){
				var gbID = WGC.insertGameBox({
					gameBoxLayerId: Tools.selectedLayer,
					name: "",
					posX: nrX,
					posY: nrY,
					defaultStateId: null,
				});
				var sID = WGC.insertGameBoxState({
					gameBoxId: gbID,
					name: "",
					boxId: Tools.selectedBox,
					isVisible: true,
				});
				WGC.data.gamebox[gbID].defaultStateId = sID;
			}
		
		}
	};
	
	var eraseBox = function(nrX, nrY){
		if(lX != nrX || lY != nrY){
	
			WGC.removeGameBox({
				gameBoxLayerId: Tools.selectedLayer,
				posX: nrX,
				posY: nrY,
			});
		
		}
	};
	
	var setEntity = function(posX, posY){
		var eX = posX + offsetX;
		var eY = posY + offsetY;
		
		WGC.insertGameEntity({
			entityId: Tools.selectedEntity,
			posX: eX,
			posY: eY,
		});
		
		refresh();
	};
	
	var removeEntity = function(posX, posY){
		WGC.insertGameEntity({
			gameEntityId: 0, //TODO: fix this
		});
		
		refresh();
	};
	
	var getGrid = function(){
		var grid = new CAAT.ActorContainer().
				setBounds(0,0,width,height);
				
		var gridImage = new Image();
		gridImage.onload = function(){
				
			for(var i = 0; i < width; i+= 16){
				for(var j = 0; j < height; j+= 16){
					/*var rect = new CAAT.ShapeActor().
							setLocation(i,j).
							setSize(16,16).
							setFillStyle('rgba(255,0,0,0.0)').
							setShape(CAAT.ShapeActor.prototype.SHAPE_RECTANGLE).
							setStrokeStyle('rgba(0,0,0,0.5)');*/
							
					var rect = new CAAT.Actor().
						setBackgroundImage(gridImage).
						enableEvents(false).
						setPosition(i, j);
						
					grid.addChild(rect);
				}
			}
		
		};
		gridImage.src = "./resource/image/grid.png?v=" + H5.getRandom();
		
		return grid;
		
		
	};
	
	var showHScroller = function(){
		var width = $("#Creator_hScrollbar").innerWidth();
		hScrollPx = MAX_WIDTH - $("#Creator_canvas").innerWidth();
		var scWidth = 32;
		if(hScrollPx < width-32){
			scWidth = width - hScrollPx;
			hScrollByPx = true;
		} else {
			hScrollByPx = false;
		}
		$("#Creator_hScrollbar .scroller").css("width", scWidth + "px");
		$("#Creator_hScrollbar .scroller").fadeIn();
	};
	
	var showVScroller = function(){
		var height = $("#Creator_vScrollbar").innerHeight();
		vScrollPx = MAX_HEIGHT - $("#Creator_canvas").innerHeight();
		var scHeihgt = 32;
		if(vScrollPx < height-32){
			scHeihgt = height - vScrollPx;
			vScrollByPx = true;
		} else {
			vScrollByPx = false;
		}
		$("#Creator_vScrollbar .scroller").css("height", scHeihgt + "px");
		$("#Creator_vScrollbar .scroller").fadeIn();
	};
	
	var hideHScroller = function(){
		$("#Creator_hScrollbar .scroller").fadeOut();
	};
	var hideVScroller = function(){
		$("#Creator_vScrollbar .scroller").fadeOut();
	};
	
};